import tkinter as tk
from tkinter import scrolledtext
import datetime

def generate_receipt_text():
    # 生成收据文本内容
    receipt_lines = []
    
    # 顶部虚线
    receipt_lines.append("." * 40)
    
    # 单号和时间（使用当前时间）
    receipt_lines.append(f"单号: DH{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}")
    receipt_lines.append(f"时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 分隔虚线
    receipt_lines.append("." * 40)
    
    # 表头（使用格式化字符串确保对齐）
    header = f"{'名称':<18} {'数量':<6} {'单价':<10} {'金额':<10}"
    receipt_lines.append(header)
    
    # 商品信息
    items = [
        ("金士顿U盘8G", 1, 40.00),
        ("胜创16G TF卡", 1, 50.00),
        ("读卡器", 1, 8.00),
        ("网线2米", 1, 5.00),
        ("芒果干", 1, 7.00)
    ]
    
    for name, quantity, price in items:
        amount = quantity * price
        # 使用格式化字符串确保各列对齐
        line = f"{name:<18} {quantity:<6} {price:<10.2f} {amount:<10.2f}"
        receipt_lines.append(line)
    
    # 分隔虚线
    receipt_lines.append("." * 40)
    
    # 计算总计信息
    total_quantity = sum(item[1] for item in items)
    total_amount = sum(item[1] * item[2] for item in items)
    
    # 计算八折优惠
    discount_rate = 0.8
    discounted_amount = total_amount * discount_rate
    
    # 假设实收金额为折后总额
    received_amount = discounted_amount
    change = received_amount - discounted_amount
    
    # 打印总计信息，包含折扣信息
    receipt_lines.append(f"总数: {total_quantity:<3} {'':<10} 原价总额: {total_amount:.2f}")
    receipt_lines.append(f"折扣: {discount_rate*100}% {'':<10} 折后总额: {discounted_amount:.2f}")
    receipt_lines.append(f"实收: {received_amount:.2f} {'':<10} 找零: {change:.2f}")
    receipt_lines.append(f"收银: 管理员")
    
    # 底部虚线
    receipt_lines.append("." * 40)
    
    # 连接所有行，每行之间换行
    return "\n".join(receipt_lines)

def show_receipt_in_window():
    # 创建主窗口
    window = tk.Tk()
    window.title("收据")
    window.geometry("500x400")  # 设置窗口大小
    
    # 创建带滚动条的文本框
    text_area = scrolledtext.ScrolledText(window, wrap=tk.WORD, width=60, height=20, font=('SimHei', 10))
    text_area.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
    
    # 生成并插入收据内容
    receipt_text = generate_receipt_text()
    text_area.insert(tk.INSERT, receipt_text)
    
    # 使文本框只读
    text_area.config(state=tk.DISABLED)
    
    # 运行主循环
    window.mainloop()

if __name__ == "__main__":
    show_receipt_in_window()

    
